﻿/*
 * Rappelz: Endless Odyssey - The first free open source Rappelz server emulator
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Rappelz.GameServer.Network;
using System.Data.Common;
using System.Data;
using Rappelz.GameServer.Network.GameClient;

namespace Rappelz.GameServer.Database
{
    /// <summary>
    /// DBLoader_AuctionCategory
    /// </summary>
    public class DBLoader_Etc : IDBProc
    {
        GameDBManager db;
        public BaseObject m_CBObject = null;

        private enum DBFields : int
        {
            AccountId = 0,
        }

        public DBLoader_Etc(GameDBManager dbManager)
        {
            db = dbManager;
        }

        public void SetCB(BaseObject obj)
        {
            m_CBObject = obj;
        }

        public void RunCB()
        {
            if (m_CBObject != null)
                m_CBObject.onEndQuery();
        }

        public bool onProcess()
        {
            LoadMarketData();
            LoadLevelUpTableData();
            LoadSummonLevelUpTableData();
            LoadStatData();
            LoadJobData();
            LoadJobLevelData();
            LoadStateData();
            LoadBannedWordData();
            LoadEnhanceData();
            LoadAutoAccountData();
//            LoadGlobalVariableData();
            return true;
        }

        int LoadMarketData()
        {
            DbConnection conn = db.CreateConnection();
            DbCommand cmd = conn.CreateCommand();

            cmd.CommandText = "select * from MarketResource order by sort_id";
            cmd.CommandType = CommandType.Text;

            conn.Open();
            int count = 0;
            try
            {
                DbDataReaderTypeCastHelper dr = new DbDataReaderTypeCastHelper(cmd.ExecuteReader());
                while (dr.Read())
                {
                    int sort_id = dr.GetInt32(0);
                    string name = dr.GetString(1);
                    int code = dr.GetInt32(2);
                    float price_ratio = (float) dr.GetDecimal(3);
                    float huntaholic_ratio = (float) dr.GetDecimal(4);

                    ItemBaseServer item = Item.GetItemBase(code);

                    long price = (long)(price_ratio * (float) item.nPrice);
                    int hpt = (int)(huntaholic_ratio * (float) item.nHuntaholicPoint);
                    
                    GameContent.AddMarketInfo(name, sort_id, code, price, hpt);
                    count++;
                }
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                Globals.Log.Warning("Can't load MarketResource database, Sql string: {0}", e.Message);
            }
            catch (Exception ex)
            {
                Globals.Log.Error("DBLoader_Etc.LoadMarketData Exception: {0}", ex);
            }
            conn.Close();

            Globals.Log.Info("Total {0} MarketResource loaded...", count);
            return count;
        }

        int LoadLevelUpTableData()
        {
            DbConnection conn = db.CreateConnection();
            DbCommand cmd = conn.CreateCommand();

            cmd.CommandText = "select * from LevelResource";
            cmd.CommandType = CommandType.Text;

            conn.Open();
            int count = 0;
            try
            {
                DbDataReaderTypeCastHelper dr = new DbDataReaderTypeCastHelper(cmd.ExecuteReader());
                while (dr.Read())
                {
                    int level = dr.GetInt32(0);
                    long exp = dr.GetInt64(1);
                    int jp1 = dr.GetInt32(2);
                    int jp2 = dr.GetInt32(3);
                    int jp3 = dr.GetInt32(4);
                    int jp4 = dr.GetInt32(5);

                    GameContent.RegisterExpTable(level, exp, jp1, jp2, jp3, jp4);
                    count++;
                }
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                Globals.Log.Warning("Can't load LevelResource database, Sql string: {0}", e.Message);
            }
            catch (Exception ex)
            {
                Globals.Log.Error("DBLoader_Etc.LoadLevelUpTableData Exception: {0}", ex);
            }
            conn.Close();

            Globals.Log.Info("Total {0} LevelResource loaded...", count);
            return count;
        }

        int LoadSummonLevelUpTableData()
        {
            DbConnection conn = db.CreateConnection();
            DbCommand cmd = conn.CreateCommand();

            cmd.CommandText = "select * from SummonLevelResource";
            cmd.CommandType = CommandType.Text;

            conn.Open();
            int count = 0;
            try
            {
                DbDataReaderTypeCastHelper dr = new DbDataReaderTypeCastHelper(cmd.ExecuteReader());
                while (dr.Read())
                {
                    int level = dr.GetInt32(0);
                    long normal_exp = dr.GetInt64(1);
                    long growth_exp = dr.GetInt64(2);
                    long evolve_exp = dr.GetInt64(3);

                    GameContent.RegisterSummonExpTable(level, normal_exp, growth_exp, evolve_exp);

                    count++;
                }
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                Globals.Log.Warning("Can't load SummonLevelResource database, Sql string: {0}", e.Message);
            }
            catch (Exception ex)
            {
                Globals.Log.Error("DBLoader_Etc.LoadSummonLevelUpTableData Exception: {0}", ex);
            }
            conn.Close();

            Globals.Log.Info("Total {0} SummonLevelResource loaded...", count);
            return count;
        }

        int LoadStatData()
        {
            DbConnection conn = db.CreateConnection();
            DbCommand cmd = conn.CreateCommand();

            cmd.CommandText = "select * from StatResource";
            cmd.CommandType = CommandType.Text;
            

            conn.Open();
            int count = 0;
            try
            {
                DbDataReaderTypeCastHelper dr = new DbDataReaderTypeCastHelper(cmd.ExecuteReader());
                while (dr.Read())
                {
                    CreatureStat stat = new CreatureStat();
                    stat.stat_id = (short) dr.GetInt32(0);
                    stat.strength = (float) dr.GetInt32(1);
                    stat.vital = (float) dr.GetInt32(2);
                    stat.dexterity = (float)dr.GetInt32(3);
                    stat.agility = (float)dr.GetInt32(4);
                    stat.intelligence = (float)dr.GetInt32(5);
                    stat.mentality = (float)dr.GetInt32(6);
                    stat.luck = (float)dr.GetInt32(7);

                    GameContent.RegisterStatInfo(stat);

                    count++;
                }
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                Globals.Log.Warning("Can't load StatResource database, Sql string: {0}", e.Message);
            }
            catch (Exception ex)
            {
                Globals.Log.Error("DBLoader_Etc.LoadStatData Exception: {0}", ex);
            }
            conn.Close();

            Globals.Log.Info("Total {0} StatResource loaded...", count);
            return count;
        }

        int LoadJobData()
        {
            DbConnection conn = db.CreateConnection();
            DbCommand cmd = conn.CreateCommand();

            cmd.CommandText = "select * from JobResource";
            cmd.CommandType = CommandType.Text;

            conn.Open();
            int count = 0;
            try
            {
                DbDataReaderTypeCastHelper dr = new DbDataReaderTypeCastHelper(cmd.ExecuteReader());
                while (dr.Read())
                {
                    JobInfo info = new JobInfo();
                    info.id = dr.GetInt32(0);
                    info.text_id = dr.GetInt32(1);
                    info.stat_id = dr.GetInt32(2);
                    info.job_class = (sbyte)dr.GetInt32(3);
                    info.job_depth = (sbyte)dr.GetByte(4);
                    info.up_lv = dr.GetInt16(5);
                    info.available_job[0] = dr.GetInt16(6);
                    info.available_job[1] = dr.GetInt16(7);
                    info.available_job[2] = dr.GetInt16(8);
                    info.available_job[3] = dr.GetInt16(9);
                    
                    GameContent.RegisterJobInfo(info);
                    count++;
                }
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                Globals.Log.Warning("Can't load JobResource database, Sql string: {0}", e.Message);
            }
            catch (Exception ex)
            {
                Globals.Log.Error("DBLoader_Etc.LoadJobData Exception: {0}", ex);
            }
            conn.Close();

            Globals.Log.Info("Total {0} JobResource loaded...", count);
            return count;
        }

//         int LoadJobLevelData()
//         {
//             DbConnection conn = db.CreateConnection();
//             DbCommand cmd = conn.CreateCommand();
// 
//             cmd.CommandText = "select * from JobLevelBonus";
//             cmd.CommandType = CommandType.Text;
// 
//             conn.Open();
//             int count = 0;
//             try
//             {
//                 DbDataReaderTypeCastHelper dr = new DbDataReaderTypeCastHelper(cmd.ExecuteReader());
//                 while (dr.Read())
//                 {
//                     JobLevelBonus bonus = new JobLevelBonus();
//                     bonus.job_id = dr.GetInt32(0);
//                     bonus.strength[0] = (float) dr.GetDecimal(1)*100;
//                     bonus.vital[0] = (float)dr.GetDecimal(2) * 100;
//                     bonus.dexterity[0] = (float)dr.GetDecimal(3) * 100;
//                     bonus.agility[0] = (float)dr.GetDecimal(4) * 100;
//                     bonus.intelligence[0] = (float)dr.GetDecimal(5) * 100;
//                     bonus.mentality[0] = (float)dr.GetDecimal(6) * 100;
//                     bonus.luck[0] = (float)dr.GetDecimal(7) * 100;
//                     bonus.strength[1] = (float)dr.GetDecimal(8) * 100;
//                     bonus.vital[1] = (float)dr.GetDecimal(9) * 100;
//                     bonus.dexterity[1] = (float)dr.GetDecimal(10) * 100;
//                     bonus.agility[1] = (float)dr.GetDecimal(11) * 100;
//                     bonus.intelligence[1] = (float)dr.GetDecimal(12) * 100;
//                     bonus.mentality[1] = (float)dr.GetDecimal(13) * 100;
//                     bonus.luck[1] = (float)dr.GetDecimal(14) * 100;
//                     bonus.strength[2] = (float)dr.GetDecimal(15) * 100;
//                     bonus.vital[2] = (float)dr.GetDecimal(16) * 100;
//                     bonus.dexterity[2] = (float)dr.GetDecimal(17) * 100;
//                     bonus.agility[2] = (float)dr.GetDecimal(18) * 100;
//                     bonus.intelligence[2] = (float)dr.GetDecimal(19) * 100;
//                     bonus.mentality[2] = (float)dr.GetDecimal(20) * 100;
//                     bonus.luck[2] = (float)dr.GetDecimal(21) * 100;
//                     bonus.strength[3] = (float)dr.GetDecimal(22) * 100;
//                     bonus.vital[3] = (float)dr.GetDecimal(23) * 100;
//                     bonus.dexterity[3] = (float)dr.GetDecimal(24) * 100;
//                     bonus.agility[3] = (float)dr.GetDecimal(25) * 100;
//                     bonus.intelligence[3] = (float)dr.GetDecimal(26) * 100;
//                     bonus.mentality[3] = (float)dr.GetDecimal(27) * 100;
//                     bonus.luck[3] = (float)dr.GetDecimal(28) * 100;
// 
//                     GameContent.RegisterJobLevelBonusInfo(bonus);
//                     count++;
//                 }
//             }
//             catch (System.Data.SqlClient.SqlException e)
//             {
//                 Globals.Log.Warning("Can't load JobLevelBonus database, Sql string: {0}", e.Message);
//             }
//             catch (Exception ex)
//             {
//                 Globals.Log.Error("DBLoader_Etc.LoadJobLevelData Exception: {0}", ex);
//             }
//             conn.Close();
// 
//             Globals.Log.Info("Total {0} JobLevelBonus loaded...", count);
//             return count;
//         }

        int LoadJobLevelData()
        {
            /*
                        DbConnection conn = db.CreateConnection();
                        DbCommand cmd = conn.CreateCommand();

                        cmd.CommandText = "select * from NewJobLevelBonus";
                        cmd.CommandType = CommandType.Text;

                        conn.Open();
                        int count = 0;
                        try
                        {
                            DbDataReaderTypeCastHelper dr = new DbDataReaderTypeCastHelper(cmd.ExecuteReader());
                            while (dr.Read())
                            {
                                int off = 0;
                                NewJobLevelBonus.Bonus bonus = new NewJobLevelBonus.Bonus();
                                int job_id = dr.GetInt32(off++);
                                int level = dr.GetInt32(off++);
                                bonus.strength = (float)dr.GetInt32(off++);
                                bonus.vital = (float)dr.GetInt32(off++);
                                bonus.dexterity = (float)dr.GetInt32(off++);
                                bonus.agility = (float)dr.GetInt32(off++);
                                bonus.intelligence = (float)dr.GetInt32(off++);
                                bonus.mentality = (float)dr.GetInt32(off++);
                                bonus.luck = (float)dr.GetInt32(off++);

                                GameContent.RegisterJobLevelBonusInfo(level,job_id,bonus);
                                count++;
                            }
                        }
                        catch (System.Data.SqlClient.SqlException e)
                        {
                            Globals.Log.Warning("Can't load NewJobLevelBonus database, Sql string: {0}", e.Message);
                        }
                        catch (Exception ex)
                        {
                            Globals.Log.Error("DBLoader_Etc.LoadJobLevelData Exception: {0}", ex);
                        }
                        conn.Close();

                        Globals.Log.Info("Total {0} JobLevelBonus loaded...", count);
                        return count;
            */
            return 0;
        }

        int LoadStateData()
        {
            DbConnection conn = db.CreateConnection();
            DbCommand cmd = conn.CreateCommand();

            cmd.CommandText = "select * from StateResource";
            cmd.CommandType = CommandType.Text;

            conn.Open();
            int count = 0;
            try
            {
                DbDataReaderTypeCastHelper dr = new DbDataReaderTypeCastHelper(cmd.ExecuteReader());
                while (dr.Read())
                {
                    StateInfo info = new StateInfo();
                    int off = 0;
                    info.id = dr.GetInt32(off++);
                    info.name_id = dr.GetInt32(off++);
                    info.tooltip_id = dr.GetInt32(off++);
                    info.is_harmful = (sbyte)dr.GetByte(off++);
                    info.state_time_type = dr.GetInt32(off++);
                    info.state_group = dr.GetInt32(off++);
                    info.duplicate_group[0] = dr.GetInt32(off++);
                    info.duplicate_group[1] = dr.GetInt32(off++);
                    info.duplicate_group[2] = dr.GetInt32(off++);
                    info.uf_avatar = (sbyte)dr.GetByte(off++);
                    info.uf_summon = (sbyte)dr.GetByte(off++);
                    info.uf_monster = (sbyte)dr.GetByte(off++);
                    info.unkw1 = dr.GetInt16(off++); // reiteration_count
                    info.base_effect_id = dr.GetInt32(off++);
                    info.fire_interval = dr.GetInt32(off++);
                    info.elemental_type = dr.GetInt32(off++);
                    info.amplify_base = (float)dr.GetDecimal(off++);
                    info.amplify_per_skl = (float)dr.GetDecimal(off++);
                    info.add_damage_base = dr.GetInt32(off++);
                    info.add_damage_per_skl = dr.GetInt32(off++);
                    info.effect_type = dr.GetInt32(off++);

                    for(int i = 0; i < StateInfo.MAX_STATE_VALUE; ++i)
                    {
                        info.fValue[i] = (float)dr.GetDecimal(off++);
                    }

                    GameContent.RegisterStateInfo(info);
/*
                    int icon_id = dr.GetInt32(40);

	[icon_file_name] [varchar](256) NOT NULL,
	[fx_id] [int] NOT NULL,
	[pos_id] [int] NOT NULL,
	[cast_skill_id] [int] NOT NULL,
	[cast_fx_id] [int] NOT NULL,
	[cast_fx_pos_id] [int] NOT NULL,
	[hit_fx_id] [int] NOT NULL,
	[hit_fx_pos_id] [int] NOT NULL,
	[special_output_timing_id] [int] NOT NULL,
	[special_output_fx_id] [int] NOT NULL,
	[special_output_fx_pos_id] [int] NOT NULL,
	[special_output_fx_delay] [int] NOT NULL,
	[state_fx_id] [int] NOT NULL,
	[state_fx_pos_id] [int] NOT NULL,
*/

                    count++;
                }
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                Globals.Log.Warning("Can't load StateResource database, Sql string: {0}", e.Message);
            }
            catch (Exception ex)
            {
                Globals.Log.Error("DBLoader_Etc.LoadStateData Exception: {0}", ex);
            }
            conn.Close();

            Globals.Log.Info("Total {0} StateResource loaded...", count);
            return count;
        }

        int LoadBannedWordData()
        {
            DbConnection conn = db.CreateConnection();
            DbCommand cmd = conn.CreateCommand();

            cmd.CommandText = "select * from BanWordResource";
            cmd.CommandType = CommandType.Text;

            conn.Open();
            int count = 0;
            try
            {
                DbDataReaderTypeCastHelper dr = new DbDataReaderTypeCastHelper(cmd.ExecuteReader());
                while (dr.Read())
                {
                    string name = dr.GetString(0);
                    GameContent.RegisterBannedWord(name);
                    count++;
                }
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                Globals.Log.Warning("Can't load BanWordResource database, Sql string: {0}", e.Message);
            }
            catch (Exception ex)
            {
                Globals.Log.Error("DBLoader_Etc.LoadBannedWordData Exception: {0}", ex);
            }
            conn.Close();

            Globals.Log.Info("Total {0} BanWordResource loaded...", count);
            return count;
        }

        int LoadEnhanceData()
        {
            DbConnection conn = db.CreateConnection();
            DbCommand cmd = conn.CreateCommand();

            cmd.CommandText = "select * from EnhanceResource";
            cmd.CommandType = CommandType.Text;

            conn.Open();
            int count = 0;
            try
            {
                DbDataReaderTypeCastHelper dr = new DbDataReaderTypeCastHelper(cmd.ExecuteReader());
                while (dr.Read())
                {
                    int off = 0;
                    EnhanceInfo info = new EnhanceInfo();
                    info.nSID = dr.GetInt32(off++);
                    info.Flag = (uint)dr.GetByte(off++);
                    info.nFailResult = dr.GetByte(off++,0);
                    info.nMaxEnhance = dr.GetByte(off++);
                    info.nLocalFlag = (uint)dr.GetInt32(off++);
                    info.nNeedItemCode = dr.GetInt32(off++);
                    for(int i = 0; i < 20; ++i)
                    {
                        info.fPercentage[i] = (float)dr.GetDecimal(off++);
                    }

                    if ((GameRule.nCurrentLocalFlag & info.nLocalFlag) != 0)
                    {
                        MixManager.RegisterEnhanceInfo(info);
                    }
                    count++;
                }
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                Globals.Log.Warning("Can't load EnhanceResource database, Sql string: {0}", e.Message);
            }
            catch (Exception ex)
            {
                Globals.Log.Error("DBLoader_Etc.LoadEnhanceData Exception: {0}", ex);
            }
            conn.Close();

            Globals.Log.Info("Total {0} EnhanceResource loaded...", count);
            return count;
        }

        int LoadAutoAccountData()
        {
            DbConnection conn = GameDBManager.Instance.CreateConnection();
            DbCommand cmd = conn.CreateCommand();

            cmd.CommandText = "smp_read_auto_account_list";
            cmd.CommandType = CommandType.StoredProcedure;

            conn.Open();
            int count = 0;
            try
            {
                DbDataReaderTypeCastHelper dr = new DbDataReaderTypeCastHelper(cmd.ExecuteReader());
                while (dr.Read())
                {
                    int account_id = dr.GetInt32(0);
                    Player.AddToAutoAccountList(account_id);
                    count++;
                }
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                Globals.Log.Warning("Can't execute smp_read_auto_account_list, Sql string: {0}", e.Message);
            }
            catch (Exception ex)
            {
                Globals.Log.Error("DBLoader_Etc.LoadAutoAccountData Exception: {0}", ex);
            }
            conn.Close();

            Globals.Log.Info("Total {0} AutoAccounts loaded...", count);
            return count;
        }

        int LoadGlobalVariableData()
        {
            DbConnection conn = db.CreateConnection();
            DbCommand cmd = conn.CreateCommand();

            cmd.CommandText = "select * from GlobalVariable";
            cmd.CommandType = CommandType.Text;

            conn.Open();
            int count = 0;
            try
            {
                DbDataReaderTypeCastHelper dr = new DbDataReaderTypeCastHelper(cmd.ExecuteReader());
                while (dr.Read())
                {
                    string name = dr.GetString(1);
                    string value = dr.GetString(2);
                    //GlobalVariableManager.Set(name, value);
                    count++;
                }
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                Globals.Log.Warning("Can't load GlobalVariable database, Sql string: {0}", e.Message);
            }
            catch (Exception ex)
            {
                Globals.Log.Error("DBLoader_Etc.LoadGlobalVariableData Exception: {0}", ex);
            }
            conn.Close();

            Globals.Log.Info("Total {0} GlobalVariables loaded...", count);
            return count;
        }
    }
}
